<template>
  <div class="container">
    <editPageNew
      ref="editPage"
      :showMore="showMore"
      :rightBtnArr="rightBtnArr"
      :moreBtnArr="moreBtnArr"
      :creatInfo="creatInfo"
      showTopTitle
    >
      <template slot="editPageTitle">
        <span class="title">机组开停机日志</span>
      </template>
      <div class="status-text">确认状态： {{ statusText }}</div>
      <div class="status-text">试机状态： {{ statusTest }}</div>
      <el-collapse v-model="activeNames">
        <el-collapse-item name="1">
          <template slot="title"> 基本信息 </template>
          <editForm
            :formConfig="basicConfig"
            ref="basicForm"
            :formData="basicFormData"
          >
          </editForm>
        </el-collapse-item>
        <el-collapse-item name="2" v-if="pageType != 'unconfirmed'">
          <template slot="title"> 变更记录 </template>
          <baseTable :tableSetting="tableSetting" ref="tableParam"></baseTable>
        </el-collapse-item>
      </el-collapse>
      <dialogPublic
        title="申请变更"
        :show.sync="changeShow"
        @doSubmit="changeSubmit"
        @doClose="() => (changeShow = false)"
        :noFootBtn="false"
        fullscreen
      >
        <editForm
          :formConfig="changeConfig"
          ref="changeForm"
          :formData="changeFormData"
        >
        </editForm>
      </dialogPublic>
      <dialogPublic
        :title="dialogTitle"
        :show.sync="dialogShow"
        @doSubmit="dialogSubmit"
        @doClose="() => (dialogShow = false)"
        :noFootBtn="noFootBtn"
        fullscreen
      >
        <titleName :titleName="'变更信息'"></titleName>
        <editForm
          :formConfig="dialogConfig"
          ref="dialogForm"
          :formData="dialogFormData"
        >
        </editForm>
        <titleName :titleName="'批复信息'"></titleName>
        <editForm
          :formConfig="confirmConfig"
          ref="confirmForm"
          :formData="confirmData"
        >
        </editForm>
      </dialogPublic>
    </editPageNew>
  </div>
</template>
<script>
import titleName from "./title.vue";
import {
  logDetails,
  updateInfo,
  logDelete,
  confirm,
  isTest,
  changeData,
  getChangeData,
  adoptData,
  toVoid,
} from "@/api/operationManagement/runLog.js";
export default {
  components: {
    titleName,
  },
  data() {
    return {
      pageName: "开停机日志",
      userInfo: {},
      id: "",
      pageType: "unconfirmed",
      statusText: "", // 当前状态
      statusTest: "",
      showMore: true, // 显示更多
      activeNames: ["1"],
      creatInfo: {},
      changeShow: false, // 申请变更弹框
      dialogTitle: "", // 弹框标题
      dialogShow: false, // 显示弹框
      noFootBtn: false, // 弹框按钮
      // 基本信息表单
      basicConfig: {
        labelWidth: "121px",
        itemArr: [
          {
            label: "设备名称",
            prop: "equipmentName",
            idsStr: "equipmentId",
            type: "text",
            span: 8,
            required: true,
          },
          {
            label: "设备管理单位",
            prop: "deptManageName", //多选时，字段要为数组类型
            propArr: "deptManageNameArr",
            idsStr: "deptManage",
            multiple: false, //是否多选
            type: "dept-select", //类型
            trigger: "change",
            disabled: true,
            span: 8,
          },
          {
            label: "操作类型",
            prop: "operateType",
            type: "select",
            span: 8,
            required: true,
            selectOption: this.$store.getters["dirtData"](
              "dispatch_operate_type"
            ),
          },
          {
            label: "计划类型",
            prop: "inPlan",
            trigger: "change",
            type: "radio",
            span: 8,
            required: true,
            radioOption: [
              {
                value: 1,
                label: "计划内",
              },
              {
                value: 0,
                label: "计划外",
              },
            ],
          },
          {
            label: "操作时间",
            prop: "operateTime",
            type: "datetime",
            trigger: "change",
            span: 8,
            required: true,
          },
          {
            label: "操作人",
            prop: "operateUserMan",
            idsStr: "operateUser",
            type: "user",
            span: 8,
          },
          {
            label: "操作原因",
            prop: "content",
            type: "textarea",
            span: 24,
            rows: 8,
            placeholder: "请输入",
          },
        ],
      },
      // 基本信息表单数据
      basicFormData: {},
      // 弹框申请变更信息表单
      changeConfig: {
        labelWidth: "121px",
        itemArr: [
          {
            label: "设备名称",
            prop: "equipmentName",
            idsStr: "equipmentId",
            type: "text",
            span: 8,
            required: true,
            disabled: true,
          },
          {
            label: "设备管理单位",
            prop: "deptManageName", //多选时，字段要为数组类型
            propArr: "deptManageNameArr",
            idsStr: "deptManage",
            multiple: false, //是否多选
            type: "dept-select", //类型
            trigger: "change",
            disabled: true,
            span: 8,
          },
          {
            label: "操作类型",
            prop: "operateType",
            type: "select",
            span: 8,
            required: true,
            selectOption: this.$store.getters["dirtData"](
              "dispatch_operate_type"
            ),
          },
          {
            label: "计划类型",
            prop: "inPlan",
            trigger: "change",
            type: "radio",
            span: 8,
            required: true,
            radioOption: [
              {
                value: 1,
                label: "计划内",
              },
              {
                value: 0,
                label: "计划外",
              },
            ],
          },
          {
            label: "操作时间",
            prop: "operateTime",
            type: "datetime",
            trigger: "change",
            span: 8,
            required: true,
          },
          {
            label: "操作人",
            prop: "operateUserMan",
            idsStr: "operateUser",
            type: "user",
            span: 8,
          },
          {
            label: "操作原因",
            prop: "content",
            type: "textarea",
            span: 24,
            rows: 8,
            placeholder: "请输入",
          },
          {
            label: "变更原因",
            prop: "changeDescription",
            type: "textarea",
            span: 24,
            rows: 8,
            placeholder: "请输入",
            required: true,
          },
          {
            label: "申请时间",
            prop: "appTime",
            type: "datetime",
            trigger: "change",
            span: 8,
            disabled: true,
          },
          {
            label: "申请人",
            prop: "appPersonName",
            idsStr: "appPerson",
            type: "user",
            span: 8,
            disabled: true,
          },
        ],
      },
      // 弹框申请变更信息表单数据
      changeFormData: {},
      // 弹框变更信息表单
      dialogConfig: {
        labelWidth: "121px",
        itemArr: [
          {
            label: "设备名称",
            prop: "equipmentName",
            idsStr: "equipmentId",
            type: "text",
            span: 8,
            required: true,
            disabled: true,
          },
          {
            label: "设备管理单位",
            prop: "deptManageName", //多选时，字段要为数组类型
            propArr: "deptManageNameArr",
            idsStr: "deptManage",
            multiple: false, //是否多选
            type: "dept-select", //类型
            trigger: "change",
            disabled: true,
            span: 8,
          },
          {
            label: "操作类型",
            prop: "operateType",
            type: "select",
            span: 8,
            required: true,
            disabled: true,
            selectOption: this.$store.getters["dirtData"](
              "dispatch_operate_type"
            ),
          },
          {
            label: "计划类型",
            prop: "inPlan",
            trigger: "change",
            type: "radio",
            span: 8,
            required: true,
            radioOption: [
              {
                value: 1,
                label: "计划内",
              },
              {
                value: 0,
                label: "计划外",
              },
            ],
          },
          {
            label: "操作时间",
            prop: "operateTime",
            type: "datetime",
            trigger: "change",
            span: 8,
            required: true,
            disabled: true,
          },
          {
            label: "操作人",
            prop: "operateUserMan",
            idsStr: "operateUser",
            type: "user",
            disabled: true,
            span: 8,
          },
          {
            label: "操作原因",
            prop: "content",
            type: "textarea",
            span: 24,
            rows: 8,
            disabled: true,
          },
          {
            label: "变更原因",
            prop: "changeDescription",
            type: "textarea",
            span: 24,
            rows: 8,
            required: true,
            disabled: true,
          },
          {
            label: "申请时间",
            prop: "appTime",
            type: "datetime",
            trigger: "change",
            span: 8,
            disabled: true,
          },
          {
            label: "申请人",
            prop: "appPersonName",
            idsStr: "appPerson",
            type: "user",
            span: 8,
            disabled: true,
          },
        ],
      },
      // 弹框变更信息表单数据
      dialogFormData: {},
      // 弹框批复信息表单
      confirmConfig: {
        labelWidth: "121px",
        itemArr: [
          {
            label: "批复结果",
            prop: "isadopt",
            trigger: "change",
            type: "radio",
            span: 24,
            required: true,
            radioOption: [
              {
                value: true,
                label: "通过",
              },
              {
                value: false,
                label: "不通过",
              },
            ],
            methods: (val) => {
              let rules = {
                opinion: [
                  {
                    required: !val.value,
                    message: "请输入批复意见",
                    trigger: "blur",
                  },
                ],
              };
              this.$refs.confirmForm.setItemArrRules(rules);
            },
          },
          {
            label: "批复意见",
            prop: "opinion",
            type: "textarea",
            span: 24,
            rows: 8,
            placeholder: "请输入",
          },
          {
            label: "操作时间",
            prop: "replyTime",
            type: "datetime",
            trigger: "change",
            span: 8,
            disabled: true,
          },
          {
            label: "批复人",
            prop: "updateByName",
            idsStr: "updateBy",
            type: "user",
            span: 8,
            disabled: true,
          },
        ],
      },
      // 弹框批复信息表单数据
      confirmData: {},
      tableSetting: {
        indexShow: true, // 序号显示
        height: 640,
        column: [
          {
            label: "申请人",
            prop: "appPersonName",
            type: "text",
            width: "100px",
          },
          {
            label: "申请时间",
            prop: "appTime",
            type: "text",
            width: "200px",
          },
          {
            label: "变更原因",
            prop: "changeDescription",
            type: "text",
          },
          {
            label: "批复结果",
            prop: "isadopt",
            type: "text",
            width: "80px",
            formatter: (row) => {
              let types = "";
              if (row.isadopt) {
                types = "通过";
              } else if (row.isadopt === false) {
                types = "不通过";
              } else {
                types = "待批复";
              }
              return types;
            },
          },
          {
            label: "操作",
            type: "button",
            scopeType: "textButton",
            width: "300px",
            buttonArr: [
              {
                text: "批复",
                icon: "icon-a-zaicishenhe",
                isShow: (row) => {
                  let flag = true;
                  if (row.isadopt === true) {
                    flag = false;
                  } else if (row.isadopt === false) {
                    flag = false;
                  } else if (this.basicFormData.isConfirm == 4) {
                    flag = false;
                  }
                  return flag;
                },
                methods: (row) => {
                  this.noFootBtn = false;
                  this.dialogTitle = "批复";
                  this.getChangeInfo(row.id);
                },
              },
              {
                text: "变更详情",
                isShow: (row) => {
                  return row.isadopt === true || row.isadopt === false;
                },
                methods: (row) => {
                  this.noFootBtn = true;
                  this.dialogTitle = "变更详情";
                  this.confirmConfig.itemArr.forEach((item) => {
                    item.disabled = true;
                  });
                  this.getChangeInfo(row.id);
                },
              },
            ],
          },
        ],
        data: [],
      },
    };
  },
  computed: {
    // 操作按钮
    rightBtnArr() {
      let arr = [
        {
          text: "保存",
          icon: "icon-baocun",
          disabled: !this.$store.getters.isBtnAuth("save"),
          content: "未授权的功能",
          methods: () => {
            this.save();
          },
          hide: true,
        },
        {
          text: "删除",
          icon: "icon-shanchu",
          disabled: !this.$store.getters.isBtnAuth("inDelete"),
          content: "未授权的功能",
          methods: () => {
            this.toChange("delete");
          },
          hide: true,
        },
        {
          text: "确认",
          icon: "icon-tijiao",
          disabled: !this.$store.getters.isBtnAuth("inConfirm"),
          content: "未授权的功能",
          methods: async () => {
            let data = await this.$refs.basicForm.getFormData();
            await updateInfo(data).then((res) => {
              if (res.code == 200) {
                if (data.operateType == "DOWN_FAIL") {
                  this.$message.warning(
                    "停机不成功不允许确认,请先修改操作类型。"
                  );
                } else {
                  this.toChange("confirmed", data);
                }
              }
            });
          },
          hide: true,
        },
        {
          text: "试机",
          icon: "icon-shiji",
          disabled: !this.$store.getters.isBtnAuth("inCommissioning"),
          content: "未授权的功能",
          methods: async () => {
            let data = await this.$refs.basicForm.getFormData();
            await updateInfo(data).then((res) => {
              if (res.code == 200) {
                if (data.operateType == "DOWN_FAIL") {
                  this.$message.warning(
                    "停机不成功不允许试机,请先修改操作类型。"
                  );
                } else {
                  this.toChange("commissioning", data);
                }
              }
            });
          },
          hide: true,
        },
        {
          text: "申请变更",
          icon: "icon-biangeng",
          disabled: !this.$store.getters.isBtnAuth("change"),
          content: "未授权的功能",
          methods: () => {
            this.changeFormData = Object.assign(this.basicFormData, {
              changeDescription: "",
              deptManageNameArr: this.basicFormData.deptManageNameArr,
              appPerson: this.userInfo.account,
              appPersonName: this.userInfo.name,
              appTime: this.$utils.getCurrentDate("minutes"),
            });
            this.changeShow = true;
          },
          hide: true,
        },
        {
          text: "作废",
          icon: "el-icon-delete",
          disabled: !this.$store.getters.isBtnAuth("invalid"),
          content: "未授权的功能",
          methods: () => {
            this.toInvalid();
          },
          hide: false,
        },
      ];
      return arr;
    },
    // 更多按钮
    moreBtnArr() {
      let arr = [
        {
          text: "操作记录",
          disabled: !this.$store.getters.isBtnAuth("operationRecords"),
          content: "未授权的功能",
          methods: () => {
            this.$refs.editPage.showOperate();
          },
        },
      ];
      return arr;
    },
  },
  created() {
    this.init();
  },
  mounted() {},
  methods: {
    toInvalid() {
      this.$confirm(`是否将数据作废吗`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        await toVoid(this.basicFormData.id).then((res) => {
          if (res.code == 200) {
            this.$utils.addOperateLog(this.id, `作废了${this.pageName}`);
            this.$message.success("作废成功");
            this.updateListData();
            setTimeout(() => {
              window.close();
            }, 1000);
          }
        });
      });
    },
    // 页面初始化信息
    init() {
      this.userInfo = this.$store.state.user.userInfo;
      this.id = this.$route.query.id;
      this.getDetails();
    },
    //获取详情信息
    async getDetails() {
      await logDetails(this.id).then((res) => {
        if (res.code == 200) {
          if (res.data.operateType == "DOWN_FAIL") {
            this.basicConfig.itemArr[2].selectOption = [
              { label: "故障停机", value: "BREAKDOWN" },
              { label: "事故跳机", value: "ACCIDENT" },
            ];
          }
          this.basicFormData = res.data;
          this.basicFormData.deptManageNameArr = res.data.deptManageName;
          this.tableSetting.data = res.data.changeDet;
          this.creatInfo = res.data;
          this.pageType = this.$route.query.pageType;
          if (res.data.isConfirm == 0) {
            this.statusText = "未确认";
            this.pageType == "unconfirmed";
            for (let i = 0; i < 4; i++) {
              this.rightBtnArr[i].hide = false;
            }
            if (res.data.isTopOne) {
              this.rightBtnArr[5].hide = false;
            }
          } else if (res.data.isConfirm == 4) {
            this.statusText = "作废";
            this.pageType == "";
            this.basicConfig.itemArr.forEach((item) => {
              item.disabled = true;
            });
          } else {
            this.activeNames.push("2");
            this.basicConfig.itemArr.forEach((item) => {
              item.disabled = true;
            });
            if (res.data.isConfirm == 1) {
              this.statusText = "已确认";
              this.pageType == "confirmed";
              this.rightBtnArr[4].hide = false;
            } else if (res.data.isConfirm == 2) {
              this.statusText = "待批复";
              this.pageType == "approved";
            }
            if (res.data.isTopOne) {
              this.rightBtnArr[5].hide = false;
            }
          }
          if (res.data.isTest) {
            this.statusTest = "试机";
          } else {
            this.statusTest = "-";
          }
          // this.pageType = this.$route.query.pageType;
          // if (this.pageType == "unconfirmed") {
          //   this.statusText = "未确认";
          //   for (let i = 0; i < 4; i++) {
          //     this.rightBtnArr[i].hide = false;
          //   }
          // } else {
          //   this.activeNames.push("2");
          //   this.basicConfig.itemArr.forEach((item) => {
          //     item.disabled = true;
          //   });
          //   if (this.pageType == "confirmed") {
          //     this.statusText = "已确认";
          //     this.rightBtnArr[4].hide = false;
          //   } else if (this.pageType == "commissioning") {
          //     this.statusText = "试机";
          //     this.rightBtnArr[4].hide = false;
          //   } else if (this.pageType == "approved") {
          //     this.statusText = "待批复";
          //   }
          // }
        }
      });
    },
    // 填写状态保存或提交
    async save() {
      let data = await this.$refs.basicForm.getFormData();
      await updateInfo(data).then((res) => {
        if (res.code == 200) {
          this.$utils.addOperateLog(this.id, `修改了${this.pageName}`);
          this.$message.success("保存成功！");
          this.updateListData();
          this.getDetails();
        }
      });
    },
    // 确认、试机、删除
    async toChange(type, data) {
      let typeText = "";
      let actionApi = () => {};
      if (type == "confirmed") {
        typeText = "确认";
        actionApi = (params) => {
          return confirm(params);
        };
      } else if (type == "commissioning") {
        typeText = "试机";
        actionApi = (params) => {
          return isTest(params);
        };
      } else {
        typeText = "删除";
        actionApi = (params) => {
          return logDelete(params);
        };
      }
      if (this.id) {
        this.$confirm(`是否将数据${typeText}`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            if (type == "confirmed" || type == "commissioning") {
              await updateInfo(data);
            }
            let val = {};
            let list = [this.id];
            if (type == "confirmed") {
              // 确认
              val = {
                isConfirm: 1,
                list,
              };
            } else if (type == "commissioning") {
              // 试机
              val = {
                isTest: true,
                list,
              };
            } else {
              // 删除
              val = list;
            }
            actionApi(val).then((res) => {
              if (res.code == 200) {
                if (type == "confirmed") {
                  // 确认
                  this.$utils.addOperateLog(this.id, `确认了${this.pageName}`);
                } else if (type == "commissioning") {
                  // 试机
                  this.$utils.addOperateLog(this.id, `试机了${this.pageName}`);
                } else {
                  // 删除
                  this.$utils.addOperateLog(this.id, `删除了${this.pageName}`);
                }
                this.$message.success("操作成功！");
                this.updateListData();
                if (type == "delete") {
                  this.$refs.editPage.closePage();
                } else {
                  let obj = {
                    pageType: type,
                    id: this.id,
                  };
                  this.$router.push({
                    query: obj,
                  });
                  this.getDetails();
                }
              }
            });
          })
          .catch((e) => {});
      } else {
        this.$message.warning("当前信息没有保存。");
      }
    },
    // 弹框确定提交-批复
    async dialogSubmit() {
      let data = await this.$refs.confirmForm.getFormData();
      data = {
        id: this.dialogFormData.id,
        isadopt: data.isadopt,
        opinion: data.opinion || "",
      };
      await adoptData(data).then((res) => {
        if (res.code == 200) {
          this.$utils.addOperateLog(this.id, `批复了${this.pageName}`);
          this.$message.success("操作成功！");
          this.updateListData();
          let obj = {
            pageType: "confirmed",
            id: this.id,
          };
          this.$router.push({
            query: obj,
          });
          this.getDetails();
          this.dialogShow = false;
        }
      });
    },
    // 弹框确定提交-申请变更
    async changeSubmit() {
      let data = await this.$refs.changeForm.getFormData();
      data.sourceId = data.id;
      delete data.id;
      await changeData(data).then((res) => {
        if (res.code == 200) {
          this.$utils.addOperateLog(this.id, `申请变更了${this.pageName}`);
          this.$message.success("操作成功！");
          this.updateListData();
          let obj = {
            pageType: "approved",
            id: this.id,
          };
          this.$router.push({
            query: obj,
          });
          this.getDetails();
          this.changeShow = false;
        }
      });
    },
    // 获取变更数据
    async getChangeInfo(id) {
      await getChangeData(id).then((res) => {
        if (res.code == 200) {
          this.dialogFormData = res.data;
          this.dialogFormData.deptManageNameArr = res.data.deptManageName;
          this.dialogFormData.inPlan = res.data.inPlan ? 1 : 0;
          if (this.dialogTitle == "批复") {
            this.confirmData = Object.assign(res.data, {
              isadopt: true,
              replyTime: this.$utils.getCurrentDate("minutes"),
              updateByName: this.userInfo.name,
              updateBy: this.userInfo.account,
            });
          } else {
            this.confirmData = res.data;
          }
          this.dialogShow = true;
        }
      });
    },
    /* 更新列表页的数据 */
    updateListData() {
      /* 通过localStorage来实现浏览器不同窗口之间的通信 */
      let num = Math.floor(Math.random() * 1000) + 1; //产生随机数，保证每次的值都不一样
      localStorage.setItem("update", num); //设置localStorage里面的值，保证每次都会触发storage事件
    },
  },
};
</script>
<style lang="less" scoped>
.container {
  height: 100%;
  width: 100%;
  background-color: #ffffff;
  .status-text {
    padding-bottom: 10px;
    text-align: left;
  }
  .title {
    font-size: 14px;
    font-weight: 500;
    color: #000;
    background: #f2f2f2;
    padding: 4px 10px;
    border-radius: 14px;
  }
  .clearF::after {
    content: "";
    display: block;
    clear: both;
    overflow: hidden;
    height: 0;
  }
  .basic {
    position: relative;
    top: 97px;
    z-index: 1;
    background: #fff;
    float: right;
    height: 28px;
    width: 50%;
  }
  /deep/ .el-textarea__inner {
    font-size: 14px;
  }
}
</style>